import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { prisma } from "../db";

export default NextAuth({
  // BUG: login and logout, then login will bring OAuthCallbackError, seems not expect result from provider
  // https://next-auth.js.org/errors#oauth_callback_error-expected-200-ok-with-body-but-no-body-was-returned
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        telephone: { label: "用户名", type: "text" },
        password: { label: "密码", type: "password" },
      },
      async authorize(credentials) {
        // Add logic here to look up the user from the credentials supplied
        const account = await prisma.user.findUnique({
          where: {
            account: {
              telephone: credentials!.telephone,
              password: credentials!.password,
            },
          },
        });

        if (account) {
          return account;
        } else {
          // If you return null then an error will be displayed advising the user to check their details.
          return null;
          // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
        }
      },
    }),
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  pages: {
    signIn: "/signin",
  },
  // session: {
  // strategy: "jwt",
  // },
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        token.user = account;
      }
      return token;
    },
    async session({ session, token }) {
      session.user.id = token.user.providerAccountId;
      return session;
    },

    // session: async ({ session, user,token }) => {
    //   console.log("user:", user);
    //   // console.log('session.user:',userAccount)
    //   // console.log(session)
    //   return session;
    // },
    // async jwt({ token, user }) {
    //   if (user) {
    //     token.user = user;
    //   }
    //   return token;
    // },
  },
});
